package edu.unlv.cs.ladders.web;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;

import edu.unlv.cs.ladders.entities.Event;
import edu.unlv.cs.ladders.entities.Score;
import edu.unlv.cs.ladders.entities.Team;
import edu.unlv.cs.ladders.services.PermissionService;

import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;

@RequestMapping("/score/**")
@Controller
public class ScoreController {

	@PreAuthorize("hasRole('ROLE_PARTICIPANT')")
    @RequestMapping(value = "/score", method = RequestMethod.POST)
    public String create(@Valid Score score, BindingResult result, ModelMap modelMap) {
        if (score == null) throw new IllegalArgumentException("A score is required");
        if (result.hasErrors()) {
            modelMap.addAttribute("score", score);
            modelMap.addAttribute("events", Event.findAllEvents());
            modelMap.addAttribute("teams", Team.findAllTeams());
            return "score/create";
        }
        score.persist();
        getPermissionService().setDefaultPermissions(score);
        return "redirect:/score/" + score.getId();
    }
    
	@PreAuthorize("hasRole('ROLE_PARTICIPANT')")
    @RequestMapping(value = "/score/form", method = RequestMethod.GET)
    public String createForm(ModelMap modelMap) {
        modelMap.addAttribute("score", new Score());
        modelMap.addAttribute("events", Event.findAllEvents());
        modelMap.addAttribute("teams", Team.findAllTeams());
        return "score/create";
    }
    
    @RequestMapping(value = "/score/{id}", method = RequestMethod.GET)
    public String show(@PathVariable("id") Long id, ModelMap modelMap) {
        if (id == null) throw new IllegalArgumentException("An Identifier is required");
        modelMap.addAttribute("score", Score.findScore(id));
        return "score/show";
    }
    
    @RequestMapping(value = "/score", method = RequestMethod.GET)
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, ModelMap modelMap) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            modelMap.addAttribute("scores", Score.findScoreEntries(page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo));
            float nrOfPages = (float) Score.countScores() / sizeNo;
            modelMap.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            modelMap.addAttribute("scores", Score.findAllScores());
        }
        modelMap.addAttribute("event_dateOfEvent_date_format", org.joda.time.format.DateTimeFormat.patternForStyle("S-", org.springframework.context.i18n.LocaleContextHolder.getLocale()));
        return "score/list";
    }
    
    @PreAuthorize("hasPermission(#score,'write') or hasRole('ROLE_COORDINATOR')")
    @RequestMapping(method = RequestMethod.PUT)
    public String update(@Valid Score score, BindingResult result, ModelMap modelMap) {
        if (score == null) throw new IllegalArgumentException("A score is required");
        if (result.hasErrors()) {
            modelMap.addAttribute("score", score);
            modelMap.addAttribute("events", Event.findAllEvents());
            modelMap.addAttribute("teams", Team.findAllTeams());
            return "score/update";
        }
        score.merge();
        return "redirect:/score/" + score.getId();
    }
    
    @PreAuthorize("hasPermission(#id,'edu.unlv.cs.ladders.entities.Score','write') or hasRole('ROLE_COORDINATOR')")
    @RequestMapping(value = "/score/{id}/form", method = RequestMethod.GET)
    public String updateForm(@PathVariable("id") Long id, ModelMap modelMap) {
        if (id == null) throw new IllegalArgumentException("An Identifier is required");
        modelMap.addAttribute("score", Score.findScore(id));
        modelMap.addAttribute("events", Event.findAllEvents());
        modelMap.addAttribute("teams", Team.findAllTeams());
        return "score/update";
    }
    
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @RequestMapping(value = "/score/{id}", method = RequestMethod.DELETE)
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size) {
        if (id == null) throw new IllegalArgumentException("An Identifier is required");
        Score.findScore(id).remove();
        return "redirect:/score?page=" + ((page == null) ? "1" : page.toString()) + "&size=" + ((size == null) ? "10" : size.toString());
    }
    
	private PermissionService permissionService;
	@Autowired
	public void setPermissionService(PermissionService permissionService) {
		this.permissionService = permissionService;
	}


	public PermissionService getPermissionService() {
		return permissionService;
	}

}
